package top.milkbox.core;

import lombok.AllArgsConstructor;
import lombok.Data;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * 绘制姓名到图片中
 *
 * @author milkbox
 */
@Data
@AllArgsConstructor
public class DrawName {
    private int fontSize = 200; // 字体大小
    private int fontStyle = Font.BOLD; // 字体风格
    private String fontName = "黑体"; // 字体名称
    private Color penColor = Color.RED; // 颜色

    private String extension; // 生成的图片文件后缀
    private File templatePictureFile; // 模板图片
    private String outputPath; // 输出路径

    /**
     * 初始化方法
     *
     * @param templatePictureFile 模板图片
     * @param outputPath          输出路径
     */
    public DrawName(File templatePictureFile, String outputPath) {
        this.templatePictureFile = templatePictureFile;
        this.outputPath = outputPath;
        this.extension = templatePictureFile.getName().substring(templatePictureFile.getName().lastIndexOf(".") + 1);
        log("绘图工具初始化完成");
    }

    /**
     * 将一个姓名绘制到图片中
     *
     * @param name 姓名
     * @throws IOException IO异常
     */
    public void drawOne(String name) throws IOException {
        log("正在绘制 " + name + " 到模板......");
        // 读取模板图片
        BufferedImage bufferedImage = ImageIO.read(this.templatePictureFile);

        // 通过图片创建大小相同的画板
        Graphics2D graphics2D = bufferedImage.createGraphics();

        graphics2D.setColor(penColor);
        graphics2D.setFont(new Font(fontName, fontStyle, fontSize));
        // 居中绘制文字
        graphics2D.drawString(
                name,
                bufferedImage.getWidth() / 2 - name.length() * fontSize / 2,
                bufferedImage.getHeight() / 2 + fontSize / 2);

        graphics2D.dispose();

        ImageIO.write(
                bufferedImage,
                "png",
                new File(this.outputPath + name + "." + this.extension));
        log("已将 " + name + " 绘制到 " + this.outputPath + name + "." + this.extension);

    }

    /**
     * 将多个姓名通过模板分别绘制到对应的图片中
     *
     * @param nameList 姓名列表
     * @throws IOException IO异常
     */
    public void drawList(List<String> nameList) throws IOException {
        for (int i = 0; i < nameList.size(); i++) {
            drawOne(nameList.get(i));
            log("进度：" + ((double) (i + 1) / nameList.size() * 100) + "%");
        }
    }

    private void log(String msg) {
        System.out.println("------> " + msg);
    }

}
